package com.cindata

import com.cindata.dictionary.*
import grails.transaction.Transactional
import grails.converters.JSON

import java.security.MessageDigest
import java.text.SimpleDateFormat

import com.cindata.dictionary.*

@Transactional
class AccountService
{

    static scope = "singleton"

    AccountFlowStageService accountFlowStageService
    AccountFlowStageConditionService accountFlowStageConditionService
    AccountFlowStageEventService accountFlowStageEventService
    AccountFlowStageRoleService accountFlowStageRoleService
    AccountFlowStageNotificationService accountFlowStageNotificationService

    // 递归查出所有上级机构
    def getAllParent(Account account, List accountList)
    {
        accountList.add(account)
        if (!account?.parent)
        {
            return accountList
        }
        else
        {
            getAllParent(account?.parent, accountList)
        }
    }

    def accountInserts(List<Map> accountMapList)
    {
        def AccountLevelArr = AccountLevelDict.all
        def AccountArr = Account.all
        def ProvinceArr = Province.all
        def CityArr = City.all
        def DistrictArr = District.all

        accountMapList.each { Map param ->

            AccountArr = Account.all

            param.level = param.level ? AccountLevelArr.find { it.name == param.level } : null
            param.parent = param.parent ? AccountArr.find { it.name == param.parent } : null
            param.province = param.province ? ProvinceArr.find { it.name == param.province } : null
            param.city = param.city ? CityArr.find { it.name == param.city } : null
            param.district = param.district ? DistrictArr.find { it.name == param.district } : null

            def account = new Account(param)
            if (account.validate())
            {
                account.save flush: true

                // 递归查出所有上级机构（包括自己）
                def accountList = getAllParent(account, [])
                accountList?.each {
                    def accountManageAccount = new AccountManageAccount()
                    accountManageAccount.account = it
                    accountManageAccount.manageAccount = account
                    accountManageAccount.save()
                }
            }
            else
            {
                println account.errors
            }
        }
        return
    }

    // 初始化机构登记流程
    def initAccountFlowStage(Account account, Workflow workflow = null)
    {
        if (!workflow)
        {
            def bankAccount = account?.createBy?.account
            workflow = AccountFlow.find("from AccountFlow where account.id = ? and accountType.id = ?", [bankAccount?.id, bankAccount.type?.id])?.workflow
        }

        if (workflow)
        {
            accountFlowStageService.initFlowStage(account, workflow)
            accountFlowStageConditionService.initFlowStageCondition(account, workflow)
            accountFlowStageEventService.initFlowStageEvent(account, workflow)
            accountFlowStageRoleService.initFlowStageRole(account, workflow)
            accountFlowStageNotificationService.initFlowStageNotification(account, workflow)

            def flowFirstStage = WorkflowStage.find("from WorkflowStage where workflow.id = ? order by executionSequence asc", [workflow?.id])
            def accountFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, flowFirstStage?.stage.id])
            if (accountFlowStage)
            {
                accountFlowStage.startTime = new Date()
                accountFlowStage.save flush: true

                account.stage = (AccountStage) flowFirstStage?.stage
                // account.status = "Pending"
                account.save flush: true
            }
        }
        else
        {
            println "未找到工作流，机构 ${account?.name} 初始化失败"
        }
    }

    // 推进
    def approve(Account account)
    {
        def map = [:]

        def currentFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, account?.stage.id])

        // 事件
        accountFlowStageEventService.evaluate(currentFlowStage, "negative")

        // 验证
        def verifyCondition = accountFlowStageConditionService.evaluate(account)
        if (!verifyCondition['flag'])
        {
            return verifyCondition
        }

        // 事件
        accountFlowStageEventService.evaluate(currentFlowStage, "positive")

        def nextFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence > ? order by executionSequence asc", [account?.id, currentFlowStage?.executionSequence])
        if (!nextFlowStage)
        {
            map['flag'] = false
            map['message'] = "找不到工作流"
            return map
        }

        // 如果 nextFlowStage 为工作流的最后一个阶段，则将 nextFlowStage endTime 赋值成当前时间,将机构状态赋值成 Completed
        def lastFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence > ? order by executionSequence asc", [account?.id, nextFlowStage?.executionSequence])

        currentFlowStage.endTime = new Date()
        currentFlowStage.processed = true
        currentFlowStage.save flush: true

        nextFlowStage.startTime = new Date()
        if (!lastFlowStage)
        {
            nextFlowStage.endTime = new Date()
            // account.status = "Completed"
        }
        nextFlowStage.save flush: true

        account.stage = (AccountStage) nextFlowStage?.stage
        account.save flush: true

        // 短信
        // accountFlowStageNotificationService.sendNotification(account)

        map['flag'] = true
        map['message'] = "成功"
        return map
    }

    // 拒绝
    Boolean reject(Account account)
    {
        def flag = false
        def currentFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and stage.id = ? order by executionSequence asc", [account?.id, account?.stage?.id])
        if (currentFlowStage?.canReject)
        {
            def previousFlowStage = AccountFlowStage.find("from AccountFlowStage where account.id = ? and executionSequence < ? and processed = true order by executionSequence desc", [account?.id, currentFlowStage?.executionSequence])
            if (previousFlowStage)
            {
                account.stage = AccountStage.find("from AccountStage where id = ?", [previousFlowStage?.stage?.id])
                if (account.validate())
                {
                    account.save flush: true

                    //发送消息
                    // accountFlowStageNotificationService.sendNotification(account)

                    flag = true
                }
                else
                {
                    account.errors.each {
                        log.info "${it}"
                    }
                }
            }
        }
        flag
    }
}
